package com.example.rtmppusher.util;

import java.util.LinkedList;

public class TaskQueue {

    boolean running = true;

    public final LinkedList<Action> actions = new LinkedList();

    final Thread thread = new Thread(() -> {
        while (running) {
            if (actions.isEmpty()) continue;
            Action action = actions.get(0);
            actions.remove(action);
            action.runAndPostException();
        }
    });

    private TaskQueue() {}

    public static TaskQueue get() {
        TaskQueue pool = new TaskQueue();
        pool.thread.start();
        return pool;
    }

    public void add(Action action) {
        actions.add(action);
    }

    public int size() {
        return actions.size();
    }

    public void clear() {
        actions.clear();
    }

    public void dispose() {
        running = false;
    }

    public interface Action {

        void run() throws Throwable;

        default void runAndPostException() {
            try {
                run();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}
